<?php

namespace System\Core;

use System\Lib\Log;
use \System\Types;

/**
 * Description of Router
 *
 * @author elton.schivei
 */
class Router extends Types\Object
{

    /**
     * @var URI
     */
    public $uri;
    public $routes = array();
    public $error_routes = array();
    public $class = '';
    public $method = 'index';
    public $directory = '';
    public $default_controller;
    private static $_instance;

    public static function &GetInstance()
    {
        if (!self::$_instance)
            self::$_instance = new self();

        return self::$_instance;
    }

    function __construct()
    {
        parent::__construct();
        $this->uri = URI::GetInstance();
        $this->SetRouting();
        Log::Write('Router Class Initialized', Log::DEBUG);
    }

    /**
     * Set the route mapping
     *
     * This function determines what should be served based on the URI request,
     * as well as any "routes" that have been set in the routing config file.
     *
     * @access	private
     * @return	void
     */
    public function SetRouting()
    {
        // Are query strings enabled in the config file?  Normally CI doesn't utilize query strings
        // since URI segments are more search-engine friendly, but they can optionally be used.
        // If this feature is enabled, we will gather the directory/class/method a little differently
        $segments = array();
        if (Config::GetValue(Config::URI, 'enable_query_strings') === true && isset($_GET[Config::GetValue(Config::URI, 'controller_trigger')]))
        {
            if (isset($_GET[Config::GetValue(Config::URI, 'directory_trigger')]))
            {
                $this->SetDirectory(trim($this->uri->_filter_uri($_GET[Config::GetValue(Config::URI, 'directory_trigger')])));
                $segments[] = $this->FetchDirectory();
            }

            if (isset($_GET[Config::GetValue(Config::URI, 'controller_trigger')]))
            {
                $this->SetClass(\trim($this->uri->_filter_uri($_GET[Config::GetValue(Config::URI, 'controller_trigger')])));
                $segments[] = $this->FetchClass();
            }

            if (isset($_GET[Config::GetValue(Config::URI, 'function_trigger')]))
            {
                $this->SetMethod(trim($this->uri->_filter_uri($_GET[Config::GetValue(Config::URI, 'function_trigger')])));
                $segments[] = $this->FetchMethod();
            }
        }

        $this->routes = \config_item('routes', \CFG_ROUTES);

        // Set the default controller so we can display it in the event
        // the URI doesn't correlated to a valid controller.
        $this->default_controller = ((!isset($this->routes['default_controller']) || $this->routes['default_controller'] == '') ? false : $this->routes['default_controller']);

        // Were there any query string segments?  If so, we'll validate them and bail out since we're done.
        if (\count($segments) > 0)
        {
            return $this->_validate_request($segments);
        }

        // Fetch the complete URI string
        $this->uri->FetchUriString();

        // Is there a URI string? If not, the default controller specified in the "routes" file will be shown.
        if ($this->uri->uri_string == '')
        {
            return $this->_set_default_controller();
        }

        // Do we need to remove the URL suffix?
        $this->uri->RemoveUrlSuffix();

        // Compile the segments into an array
        $this->uri->ExplodeSegments();

        // Parse any custom routing that may exist
        $this->_parse_routes();

        // Re-index the segment array so that it starts with 1 rather than 0
        $this->uri->ReindexSegments();
    }

    /**
     * Set the default controller
     *
     * @access	private
     * @return	void
     */
    private function _set_default_controller()
    {
        if ($this->default_controller === false)
        {
            Errors\Error::ShowErr("Unable to determine what should be displayed. A default route has not been specified in the routing file.");
        }
        // Is the method being specified?
        if (\strpos($this->default_controller, '/') !== false)
        {
            $x = \explode('/', $this->default_controller);

            $this->SetClass($x[0]);
            $this->SetMethod($x[1]);
            $this->_set_request($x);
        }
        else
        {
            $this->SetClass($this->default_controller);
            $this->SetMethod('index');
            $this->_set_request(array($this->default_controller, 'index'));
        }

        // re-index the routed segments array so it starts with 1 rather than 0
        $this->uri->ReindexSegments();

        Log::Write("No URI present. Default controller set.", Log::DEBUG);
    }

    // --------------------------------------------------------------------

    /**
     * Set the Route
     *
     * This function takes an array of URI segments as
     * input, and sets the current class/method
     *
     * @access	private
     * @param	array
     * @param	bool
     * @return	void
     */
    private function _set_request($segments = array())
    {
        $segments = $this->_validate_request($segments);

        if (\count($segments) == 0)
        {
            return $this->_set_default_controller();
        }

        $this->SetClass($segments[0]);

        if (isset($segments[1]))
        {
            // A standard method request
            $this->SetMethod($segments[1]);
        }
        else
        {
            // This lets the "routed" segment array identify that the default
            // index method is being used.
            $segments[1] = 'index';
        }

        // Update our "routed" segment array to contain the segments.
        // Note: If there is no custom routing, this array will be
        // identical to $this->uri->segments
        $this->uri->rsegments = $segments;
    }

    // --------------------------------------------------------------------

    /**
     * Validates the supplied segments.  Attempts to determine the path to
     * the controller.
     *
     * @access	private
     * @param	array
     * @return	array
     */
    private function _validate_request($segments)
    {
        if (\count($segments) == 0)
        {
            return $segments;
        }

        // Does the requested controller exist in the root folder?
        if (\file_exists(Applications::GetAppPath() . 'Controllers/' . $segments[0] . \EXT))
        {
            return $segments;
        }

        // Is the controller in a sub-folder?
        if (\is_dir(Applications::GetAppPath() . 'Controllers/' . $segments[0]))
        {
            // Set the directory and remove it from the segment array
            $this->SetDirectory($segments[0]);
            $segments = \array_slice($segments, 1);

            if (\count($segments) > 0)
            {
                // Does the requested controller exist in the sub-folder?
                if (!\file_exists(Applications::GetAppPath() . 'Controllers/' . $this->FetchDirectory() . $segments[0] . \EXT))
                {
                    Errors\Error::Show404Error($this->FetchDirectory() . $segments[0]);
                }
            }
            else
            {
                // Is the method being specified in the route?
                if (\strpos($this->default_controller, '/') !== false)
                {
                    $x = \explode('/', $this->default_controller);

                    $this->SetClass($x[0]);
                    $this->SetMethod($x[1]);
                }
                else
                {
                    $this->SetClass($this->default_controller);
                    $this->SetMethod('index');
                }

                // Does the default controller exist in the sub-folder?
                if (!\file_exists(Applications::GetAppPath() . 'Controllers/' . $this->FetchDirectory() . $this->default_controller . \EXT))
                {
                    $this->directory = '';
                    return array();
                }
            }

            return $segments;
        }


        // If we've gotten this far it means that the URI does not correlate to a valid
        // controller class.  We will now see if there is an override
        if (!empty($this->routes['404_override']))
        {
            $x = \explode('/', $this->routes['404_override']);

            $this->SetClass($x[0]);
            $this->SetMethod(isset($x[1]) ? $x[1] : 'index');

            return $x;
        }


        // Nothing else to do at this point but show a 404
        Errors\Error::Show404Error($segments[0]);
    }

    // --------------------------------------------------------------------

    /**
     *  Parse Routes
     *
     * This function matches any routes that may exist in
     * the config/routes.php file against the URI to
     * determine if the class/method need to be remapped.
     *
     * @access	private
     * @return	void
     */
    private function _parse_routes()
    {
        // Turn the segment array into a URI string
        $uri = \implode('/', $this->uri->segments);

        // Is there a literal match?  If so we're done
        if (isset($this->routes[$uri]))
        {
            return $this->_set_request(\explode('/', $this->routes[$uri]));
        }

        // Loop through the route array looking for wild-cards
        foreach ($this->routes as $key => $val)
        {
            // Convert wild-cards to RegEx
            $key = \str_replace(':any', '.+', \str_replace(':num', '[0-9]+', $key));

            // Does the RegEx match?
            if (\preg_match('#^' . $key . '$#', $uri))
            {
                // Do we have a back-reference?
                if (\strpos($val, '$') !== false && \strpos($key, '(') !== false)
                {
                    $val = \preg_replace('#^' . $key . '$#', $val, $uri);
                }

                return $this->_set_request(\explode('/', $val));
            }
        }

        // If we got this far it means we didn't encounter a
        // matching route so we'll set the site default route
        $this->_set_request($this->uri->segments);
    }

    // --------------------------------------------------------------------

    /**
     * Set the class name
     *
     * @access	public
     * @param	string
     * @return	void
     */
    public function SetClass($class)
    {
        $this->class = \str_replace(array('/', '.'), '', $class);
    }

    // --------------------------------------------------------------------

    /**
     * Fetch the current class
     *
     * @access	public
     * @return	string
     */
    public function FetchClass()
    {
        return Applications::GetAppName() . '\\Controllers\\' . ($this->class? : $this->default_controller);
    }

    // --------------------------------------------------------------------

    /**
     *  Set the method name
     *
     * @access	public
     * @param	string
     * @return	void
     */
    public function SetMethod($method)
    {
        $this->method = $method;
    }

    // --------------------------------------------------------------------

    /**
     *  Fetch the current method
     *
     * @access	public
     * @return	string
     */
    public function FetchMethod()
    {
        if ($this->method == $this->class)
        {
            return 'index';
        }

        return $this->method;
    }

    // --------------------------------------------------------------------

    /**
     *  Set the directory name
     *
     * @access	public
     * @param	string
     * @return	void
     */
    public function SetDirectory($dir)
    {
        $this->directory = \str_replace(array('/', '.'), '', $dir) . '/';
    }

    // --------------------------------------------------------------------

    /**
     *  Fetch the sub-directory (if any) that contains the requested controller class
     *
     * @access	public
     * @return	string
     */
    public function FetchDirectory()
    {
        return $this->directory;
    }

    // --------------------------------------------------------------------

    /**
     *  Set the controller overrides
     *
     * @access	public
     * @param	array
     * @return	null
     */
    public function SetOverrides($routing)
    {
        if (!\is_array($routing))
        {
            return;
        }

        if (isset($routing['directory']))
        {
            $this->SetDirectory($routing['directory']);
        }

        if (isset($routing['controller']) && $routing['controller'] != '')
        {
            $this->SetClass($routing['controller']);
        }

        if (isset($routing['function']))
        {
            $routing['function'] = ($routing['function'] == '') ? 'index' : $routing['function'];
            $this->SetMethod($routing['function']);
        }
    }

}
